package com.qysoft.dtkj.dtkj_gl.services.xtwh;

import java.math.BigDecimal;
import java.util.List;

import com.qysoft.rapid.dao.mybatis.RapidDao;
import com.qysoft.rapid.domain.Bean;
import com.qysoft.rapid.exceptions.BizException;

public class JGGLService {
	
	/**
	 * 删除机构
	 * @param jgid 机构id
	 * @throws Exception
	 */
	public static void delete(String jgid) throws Exception{
		BigDecimal count = (BigDecimal) RapidDao.queryOne("select count(1) from sys_org t where t.parentid = ?", jgid);
		if (count.longValue()>0) {
			throw new BizException("删除失败，存在下级机构！");
		}
		count = (BigDecimal) RapidDao.queryOne("select count(1) from sys_user t where t.orgid = ?", jgid);
		if (count.longValue()>0) {
			throw new BizException("删除失败，机构下存在人员信息！");
		}
		RapidDao.deleteById("sys_org", "id",jgid);
	}
	
	/**
	 * 新增机构
	 * @param jgxx
	 * @throws Exception
	 */
	public static void saveJGXX(Bean jgxx) throws Exception{
		BigDecimal count = (BigDecimal) RapidDao.queryOne("select count(1) from sys_org t where t.bm = ?", jgxx.getStr("bm"));
		if (count.longValue()>0) { 
			throw new BizException("保存失败，重复的机构编码！");
		}
		//初始化jgid
		String jgid = RapidDao.selectOneByXml("jgid_select", jgxx.getStr("parentid"));
		jgxx.set("id", jgid);
		RapidDao.save("sys_org", "id", jgxx);
	}
	
	/**
	 * 查询机构信息
	 * @param jgid 机构id
	 * @return
	 * @throws Exception
	 */
	public static Bean queryJGXX(String jgid) throws Exception{
		Bean jgxx = RapidDao.selectOneByXml("jgxx_select", jgid);
		return jgxx;
	}
	
	/**
	 * 修改机构信息
	 * @param jgxx
	 * @throws Exception
	 */
	public static void updateJGXX(Bean jgxx) throws Exception{
		BigDecimal count = (BigDecimal) RapidDao.queryOne("select count(1) from sys_org t where t.bm = ? and t.id != ?", jgxx.getStr("bm"),jgxx.getStr("id"));
		if (count.longValue()>0) {
			throw new BizException("保存失败，重复的机构代码！");
		}	
		//不可修改上级机构
		jgxx.remove("parentid");
		RapidDao.update("sys_org", "id", jgxx);
	}
        
    /**
     * 查询机构信息树
     * @param string
     * @return 
     */
    public static List<Bean> findJGXXListForTree(String sjjgid) throws Exception {
        List<Bean> jgList = RapidDao.selectListByXml("query_yygl_jgxx_tree", sjjgid);
        return jgList;
    }

    
}
